package com.spark.common.core.service;

import com.spark.common.core.entity.LoginUser;
import com.spark.common.core.entity.system.SysRole;
import com.spark.common.utils.SecurityUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Objects;

/**
 * 自定义权限校验实现
 *
 * @author LYCHEE
 * @date 2025/3/26 16:11
 */
@Service("sp")
public class PermissionService {

    /**
     * 校验是否拥有某个权限
     *
     * @param permission 权限编码
     * @return 是否有权限
     */
    public boolean hasPerm(String permission) {
        if (StringUtils.isEmpty(permission)) {
            return false;
        }
        LoginUser user = SecurityUtils.getUser();
        if (Objects.isNull(user) || CollectionUtils.isEmpty(user.getPermissions())) {
            return false;
        }
        return user.getPermissions().contains(StringUtils.trim(permission));
    }

    /**
     * 校验是否拥有某个角色
     *
     * @param role 角色编码
     * @return 是否有角色
     */
    public boolean hasRole(String role) {
        if (StringUtils.isEmpty(role)) {
            return false;
        }
        LoginUser user = SecurityUtils.getUser();
        if (Objects.isNull(user) || CollectionUtils.isEmpty(user.getUser().getRoleList())) {
            return false;
        }
        for (SysRole sysRole : user.getUser().getRoleList()){
            String roleCode = sysRole.getRoleCode();
            if (roleCode.equals(StringUtils.trim(role))){
                return true;
            }
        }
        return false;
    }

}
